import cv2
import numpy as np
from typing import List, Dict
import logging

class ImageGenerator:
    @staticmethod
    def generate_translated_image(
        image_path: str, 
        ocr_results: List[Dict], 
        translations: List[str],
        output_path: str,
        font_scale: float = 0.8,
        thickness: int = 2,
        font_color: tuple = (0, 0, 255),  # 红色
        bg_color: tuple = (255, 255, 255),  # 白色背景
        padding: int = 5
    ) -> bool:
        """生成翻译后的图片"""
        try:
            # 读取原始图片
            img = cv2.imread(image_path)
            if img is None:
                logging.error(f"无法读取图片: {image_path}")
                return False
            
            # 为每个识别区域添加翻译文本
            for result, translation in zip(ocr_results, translations):
                if not translation.strip():
                    continue
                
                # 获取文本框位置
                points = np.array(result["position"], dtype=np.int32)
                
                # 计算文本框的边界
                x_min, y_min = np.min(points, axis=0)
                x_max, y_max = np.max(points, axis=0)
                
                # 计算文本位置（放在原文本框下方）
                text_x = x_min
                text_y = y_max + 30  # 在原文本框下方留出空间
                
                # 计算文本大小
                (text_width, text_height), _ = cv2.getTextSize(
                    translation,
                    cv2.FONT_HERSHEY_SIMPLEX,
                    font_scale,
                    thickness
                )
                
                # 绘制背景矩形
                cv2.rectangle(
                    img,
                    (text_x - padding, text_y - text_height - padding),
                    (text_x + text_width + padding, text_y + padding),
                    bg_color,
                    -1  # 填充矩形
                )
                
                # 添加翻译文本
                cv2.putText(
                    img, 
                    translation, 
                    (text_x, text_y),
                    cv2.FONT_HERSHEY_SIMPLEX,
                    font_scale,
                    font_color,
                    thickness,
                    cv2.LINE_AA
                )
            
            # 保存结果图片
            success = cv2.imwrite(output_path, img)
            if not success:
                logging.error(f"无法保存图片: {output_path}")
            return success
        except Exception as e:
            logging.error(f"图片生成失败: {e}")
            return False